<script setup lang="ts">
import {
AdjustmentsHorizontal,
Api,
ArrowNarrowLeft,
Backhoe,
Barcode,
Bookmarks,
BrandTripadvisor,
ChevronDown,
Eye,
LayoutSidebarLeftCollapse,
LayoutSidebarLeftExpand,
Settings
} from '@vicons/tabler'
import { NAvatar, NButton, NGrid, NGridItem, NIcon, NScrollbar, NTag } from 'naive-ui'
import { onMounted, provide, ref } from 'vue'
import { useRouter } from 'vue-router'

import CollapsibleList from '@/components/CollapsibleList.vue'
import Context from '@/views/LLMStudio2/BuilderModelPanel/components/context.vue'
import PromptEditor from '@/views/LLMStudio2/BuilderModelPanel/components/prompt-editor/index.vue'
import Shortcuts from '@/views/LLMStudio2/BuilderModelPanel/components/Shortcuts.vue'
import Tool from '@/views/LLMStudio2/BuilderModelPanel/components/Tool.vue'
import VariableSection from '@/views/LLMStudio2/BuilderModelPanel/components/variable-section.vue'

import ChatInterface from '@/components/ChatInterface/index.vue'
import type { MessageGroupList } from '@/components/ChatInterface/type'
import { getAppById } from '@/service/api/userApp'
import type { AppItem } from '@/types/userApp'
interface MenuItem {
  type: string
  label: string
  key: string
  icon: any
  normalClass?: string
  hoverClass?: string
  activeClass?: string
}

interface Variable {
  key: string
  value: string
}

const menuItems = ref<MenuItem[]>([
  { type: 'menu', label: 'Build', key: 'build', icon: Backhoe },
  { type: 'menu', label: 'Access API', key: 'api', icon: Api },
  { type: 'menu', label: '日志', key: 'logs', icon: Barcode },
  { type: 'menu', label: '监控', key: 'monitor', icon: BrandTripadvisor },
  { type: 'menu', label: '信息标注', key: 'labeling', icon: Bookmarks },
  { type: 'menu', label: '收起', key: 'collapse', icon: LayoutSidebarLeftCollapse },
  {
    type: 'menu',
    label: '退出高级模式',
    key: 'exit',
    icon: ArrowNarrowLeft,
    normalClass: 'bg-red-400 dark:bg-dark hover:bg-#EAEFFC text-white',
    hoverClass: 'hover:bg-red-500'
  }
])

const isCollapsed = ref(false)
const menuActiveKey = ref('build')
const router = useRouter()
const currentAppId = ref(0)

const goBuilder = () => router.push(`/llm-studio/chat/${currentAppId.value}`)

const handleItemClick = (item: MenuItem) => {
  const { key } = item
  if (key === 'collapse') {
    isCollapsed.value = !isCollapsed.value
    const lastItem = menuItems.value.find(item => item.key === 'collapse')
    if (lastItem) {
      lastItem.icon = isCollapsed.value ? LayoutSidebarLeftExpand : LayoutSidebarLeftCollapse
      lastItem.label = isCollapsed.value ? '展开' : '收起'
    }
  } else if (key === 'exit') {
    goBuilder()
  } else {
    menuActiveKey.value = key
    router.push({ name: key })
  }
}

const variables = ref<Variable[]>([])

provide('variables', variables)

const addVariable = (newVariable: Variable) => variables.value.push(newVariable)

const updateVariable = (updatedVariable: Variable) => {
  const index = variables.value.findIndex(v => v.key === updatedVariable.key)
  if (index !== -1) variables.value[index] = updatedVariable
}

const deleteVariable = (key: string) => {
  variables.value = variables.value.filter(v => v.key !== key)
}

provide('addVariable', addVariable)
provide('updateVariable', updateVariable)
provide('deleteVariable', deleteVariable)

const initialMessages: MessageGroupList = [
  {
    id: 1,
    messageList: {
      messages: [
        { id: 1, sender: 'user', timestamp: Date.now(), type: 'text', content: '你好' },
        { id: 2, sender: 'bot', timestamp: Date.now(), type: 'text', content: '你好' }
      ]
    }
  },
  {
    id: 2,
    messageList: {
      messages: [
        { id: 3, sender: 'user', timestamp: Date.now(), type: 'text', content: '你好1' },
        { id: 4, sender: 'bot', timestamp: Date.now(), type: 'text', content: '你好' }
      ]
    }
  },
  {
    id: 3,
    messageList: {
      messages: [
        { id: 5, sender: 'user', timestamp: Date.now(), type: 'text', content: '我的头发' },
        { id: 6, sender: 'bot', timestamp: Date.now(), type: 'text', content: '是真发' }
      ]
    }
  },
  {
    id: 4,
    messageList: {
      messages: [
        { id: 7, sender: 'user', timestamp: Date.now(), type: 'text', content: '你好' },
        { id: 8, sender: 'bot', timestamp: Date.now(), type: 'text', content: '你好' }
      ]
    }
  }
]

const handleSendMessage = (message: string) => {
  console.log('New message:', message)
  // 这里可以添加调用API或处理响应的逻辑
}

const handleRestartConversation = () => {
  console.log('Conversation restarted')
  // 这里可以添加重置对话的逻辑
}

const currentApp = ref<Partial<AppItem>>({})

onMounted(async () => {
  currentAppId.value = router.currentRoute.value.params.id
  try {
    const app = await getAppById(currentAppId.value)
    currentApp.value = app.data
    console.log(currentApp.value)
  } catch (error) {
    console.error(error)
  }
})
</script>

<template>
  <TopNavLayout class="bg-#FCFCFD h-screen w-full">
    <div class="flex h-full w-full bg-#FCFCFD relative">
      <div class="sidebar-container">
        <div
          class="flex items-center justify-center p-5px hover:bg-gray-300 dark:hover:bg-gray-700 rounded-lg max-w-200px cursor-pointer mb-20px"
        >
          <div class="flex items-center justify-center">
            <NAvatar :src="currentApp.avatar" class="w-40px h-40px rounded-md"></NAvatar>
          </div>
          <div class="flex flex-col items-start ml-10px w-full gap-1px" v-if="!isCollapsed">
            <span class="text-12px text-gray-500 truncate max-w-120px">{{ currentApp.title }}</span>
            <!-- 超长隐藏 -->
            <div class="text-xs text-gray-500  truncate max-w-120px">
              {{ currentApp.desc }}
            </div>
            <div class="text-xs text-#444CE7 border border-solid border-#444CE7 rounded-md px-3px py-1px ">
              管理员
            </div>
          </div>
        </div>
        <CollapsibleList
          style="background-color: #fcfcfd"
          activeClass="bg-#EAEFFC color-#155aef dark:bg-dark hover:bg-#EAEFFC"
          hoverClass="hover:bg-#EAEFFC hover:dark:bg-#1b2429"
          :isCollapsed="isCollapsed"
          :modelValue="menuActiveKey"
          :menuItems="menuItems"
          @itemClick="handleItemClick"
        ></CollapsibleList>
      </div>
      <div class="content-container flex flex-col px-7 pt-3 bg-white relative w-full h-full">
        <div class="flex bg-white justify-between items-center h-50px w-full">
          <h3>编排</h3>
          <div class="flex items-center justify-center gap-10px">
            <NButton class="rounded-xl">
              <NIcon size="20" :component="Settings" class="mr-5px"></NIcon>
              Agent设置
            </NButton>
            <div
              class="rounded-xl flex items-center justify-center gap-10px py-2px px-10px bg-#eaf0f1 dark:bg-#1b2429 border-solid border-#155aef border-1px cursor-pointer"
              style="background-color: rgba(239, 244, 255, 0.5)"
            >
              <NIcon size="20" :component="Settings"></NIcon>
              <span>gpt-3.5-turbo</span>
              <div
                class="px-5px py-2px rounded text-9px border border-solid text-#444CE7 border-#444CE7"
              >
                CHAT
              </div>
              <div class="flex justify-center items-center">
                <NIcon size="16" :component="Eye" class="text-#444CE7"></NIcon>
              </div>
              <div class="px-5px py-2px ml-5px rounded text-9px flex justify-center items-center">
                <NIcon size="25" :component="AdjustmentsHorizontal" class="text-#444CE7"></NIcon>
              </div>
            </div>
            <NButton class="rounded-xl" type="primary">
              发布
              <NIcon size="20" :component="ChevronDown" class="mr-5px"></NIcon>
            </NButton>
          </div>
        </div>
        <NGrid cols="7" item-responsive responsive="screen" >
          <NGridItem span="7 l:3">
            <NScrollbar class="w-full h-full" style="height: calc(100vh - 70px)">
              <div class="w-full h-full grid gap-10px pr-20px">
                <PromptEditor></PromptEditor>
                <VariableSection></VariableSection>
                <Context></Context>
                <Tool></Tool>
                <Shortcuts></Shortcuts>
              </div>
            </NScrollbar>
          </NGridItem>
          <NGridItem span="7 l:4">
            <ChatInterface
              :initialMessages="initialMessages"
              @sendMessage="handleSendMessage"
              @restartConversation="handleRestartConversation"
            />
          </NGridItem>
        </NGrid>
      </div>
    </div>
  </TopNavLayout>
</template>

<style scoped lang="scss">
.apps-body {
  height: calc(100% - 50px);
  width: 100%;
  margin-top: 15px;
  overflow: hidden;
}
.sidebar-container {
  padding: 15px 5px 0px 5px;
  height: 100%;
  border-right: 1px solid rgba(128, 128, 128, 0.1);
  flex: 0 0 auto;
}
.content-container {
  height: 100%;
  width: calc(100% - 200px);
  overflow: hidden;
}
.monaco-editor-container {
  border: none;
  outline: none;
}

.message_body {
  height: calc(100% - 120px);
}

.message_input {
  height: 120px;
}
</style>
